package com.wzqj.agent.common.interceptor;

import com.wzqj.agent.app.login.controller.AuthRequiredController;
import com.wzqj.agent.common.exception.BusinessErrorType;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 作业APP权限控制拦截器
 * Created by wanghao@weipass.cn on 2015/7/30.
 */
public class AuthRequiredInterceptor implements HandlerInterceptor {

    private static Logger log = LogManager.getLogger();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if(handler instanceof AuthRequiredController) {
            AuthRequiredController action = (AuthRequiredController)handler;
            AuthRequiredController.RmCode code = action.preMethod(request, response);
            long errCode = 0x0101;
            try {
                switch(code) {
                    case REQUIRE_LOGIN :
                        errCode = BusinessErrorType.NOT_LOGIN.getErrCode();
                        break;
                    case REQUIRE_AUTH :
                        errCode = BusinessErrorType.TOKEN_INVALID.getErrCode();
                        break;
                    default:
                        return true;
                }
            } catch (Exception e) {
                log.error("AuthRequiredInterceptor#preHandle:" + e.getMessage());
            }
            response.sendRedirect(request.getContextPath()+"/api/login/checkLogin.xhtml?errCode="+errCode);
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
